from flask import current_app
from flask import flash
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from info.models import User
from info.modules.admin import admin_blu
from info.utils.commons import admin_login_required


@admin_blu.route('/')
@admin_login_required
def index1():
    """显示admin首页"""
    return redirect(url_for('admin.index'))


@admin_blu.route('/index')
@admin_login_required
def index():
    """显示admin首页"""
    return render_template('admin/index.html')


@admin_blu.route('/login', methods=['GET', 'POST'])
def login():
    """
    后台登陆页面
    :return:
    """
    if request.method == 'GET':
        user_id = session.get('user_id')
        is_admin = session.get('is_admin')
        if not user_id or not is_admin == True:
            return render_template('admin/login.html')
        else:
            return redirect(url_for('admin.index'))
    else:
        # 进项登陆页面
        # 接收参数 并校验
        name = request.form.get('username')
        password = request.form.get('password')
        if not all([name, password]):
            flash('参数不完整')
            return redirect(url_for('admin.login'))
        # 根据name查询管理员用户
        try:
            user = User.query.filter(User.nick_name == name, User.is_admin == True).first()
        except Exception as e:
            current_app.logger.error(e)
            flash('查询失败')
        if not user:
            flash('用户不存在')
            return redirect(url_for('admin.login'))
        # 校验密码是否正确
        if not user.check_passowrd(password):
            flash('密码错误')
            return redirect(url_for('admin.login'))
        # 在session中记住用户的登陆状态
        session['user_id'] = user.id
        session['nick_name'] = user.nick_name
        session['mobile'] = user.mobile
        session['is_admin'] = True

        # 登陆成功 跳转到后台管理首页
        return redirect(url_for('admin.index'))
